package com.example.weather;

import android.Manifest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.example.weather.R;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import pub.devrel.easypermissions.EasyPermissions;

public class MainActivity extends AppCompatActivity {

    private Button btnHttp;
    private TextView tvData;
    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            //获取消息传递的数据
            String data = (String) msg.obj;
            //更新ui界面
            tvData.setText(data);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //申请网络权限
        String[]perms = {Manifest.permission.INTERNET};
        if(!EasyPermissions.hasPermissions(this,perms)){
            EasyPermissions.requestPermissions(this,"internet",1,perms);
        }

        tvData = (TextView) findViewById(R.id.tv_data);
        btnHttp = (Button) findViewById(R.id.btn_http);
        btnHttp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击按钮，访问服务器数据
                //耗时操作，子线程执行
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        //线程要执行的操作
                        getDataFromServer();
                    }
                }).start();

            }
        });
    }

    private void getDataFromServer() {
        //1-确定访问的地址http://localhost:8080/weather.json
        //本地主机的IP：10.0.2.2
        String ip = "http://10.0.2.2:8080/weather.json";
        //2-将地址封装成url对象
        try {
            URL url = new URL(ip);
            //3-使用url开启网络连接
            HttpURLConnection con = (HttpURLConnection) url.openConnection();
            //4-设置连接超时的时间
            con.setConnectTimeout(2000);
            //5-链接成功后，获取服务器提供的输入流，读取数据
            if (con.getResponseCode() == 200) {
                InputStream is = con.getInputStream();
                String data = "";
                int len = 0;
                byte[] buf = new byte[1024];
                while ((len = is.read(buf)) != -1) {
                    data = data + new String(buf, 0, len);
                }
                //将从服务器获取的数据，输出到日志
                //Log.i("MainActivity","data="+data);
                //将数据显示到文本框,子线程不能操作ui
                //方法一runOnUiThread
                /*final String finalData = data;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //更新ui
                        tvData.setText(finalData);
                    }
                });*/
                //方法二Handler
                //创建一个消息对象
                Message msg = new Message();
                //及那个数据放到消息中
                msg.obj = data;
                //发送给主线程
                handler.sendMessage(msg);

                is.close();
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
